<?php

/**
 * @Author: liu
 * @Date:   2017-12-04 16:15:31
 * @Last Modified by:   liu
 * @Last Modified time: 2018-03-16 10:49:48
 * 用于退套餐卡销售订单的
 */


class ScsReturnServiceCardController extends BaseController
{
    
   /**
    * @Author   lyt                      <ahlyt@anhuibj.com>
    * @DateTime 2018-03-08T14:44:11+0800
    * @return   [type]                   [description]
    * 用于显示套餐卡退货单的详情
    */
    public function returnServiceCardOrderShow(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $return_order_id = Input::get('return_order_id');
            $ro=ReturnServiceCarOrder::find($return_order_id);
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $ro->amount=round($ro->amount/100,2);

            $orders=ServiceCardOrder::where('order_id',$ro->order_id)
                ->select('order_id','pay_time','service_card_detail_id','car_no','service_card_id',"amount","pay_amount","user_id","amount")
                ->first();
            $users=Users::find($orders->user_id);
            $orders->amount=round($orders->amount/100,2);
            $orders->pay_amount=round($orders->pay_amount/100,2);
            $orders->phone=$users->phone;
            $orders->user_type=$users->type;
            $scd=ServiceCardBase::find($orders->service_card_id);
            $orders->service_card_name=$scd->name;

            $opr=ServiceCardOrderPayRecord::where('order_id',$ro->order_id)->where('status',1)->select('id','pay_type','amount')->get();
            foreach ($opr as $_p) {
                $_p->amount=round($_p->amount/100,2);
            }
            $scbp=ServiceCardDetailPack::leftJoin("product_package","product_package.id","=","service_card_detail_pack.pack_id")->where("service_card_detail_pack.service_card_detail_id",$orders->service_card_detail_id)->select("service_card_detail_pack.amount","service_card_detail_pack.number","service_card_detail_pack.curr_number","product_package.name")->get();
            foreach ($scbp as $_p) {
                $_p->amount=round($_p->amount/100,2);
            }
            $return_money = [];
            $ror =[];
            // 如果状态是未执行，不返回退款结果
            if ($ro->status != 0) {
                $ror=ReturnServiceCardRecord::where('return_order_id',$return_order_id)->get(); 
                foreach ($ror as $_r) {
                    $_r->amount=round($_r->amount/100,2);
                }
                $return_order_record = ReturnServiceCardRecord::where('return_order_id',Input::get('return_order_id'))
                                        ->where('pay_type',8) 
                                        ->get()->toArray();
                
                if(!empty($return_order_record)){
                    foreach($return_order_record as $value) { //一个退款对应多个退款记录
                        $acount_user_recharge_spendre_record = AcountUserRechargeSpendRe::where('status',1)->where("type",7)->where("buss_id",$value['id'])->get()->toArray();
                        if(!empty($acount_user_recharge_spendre_record)) {
                            foreach($acount_user_recharge_spendre_record as $b_values){  //一个退款记录对应多个消费退款充值记录
                                $array = AcountUserRecharge::RechargeInfo($b_values['aurr_id']); //根据充值记录，查找对应的门店名称和账户标虚
                                $key = $array['shop_id'].'_'.$array['acount_type'];
                                if(isset($return_money[$key])){
                                    $return_money[$key]['amount'] += round(bcdiv($b_values['amount'],100,6),2);
                                } else {
                                    $return_money[$key] = $array;
                                    $return_money[$key]['amount'] = round(bcdiv($b_values['amount'],100,6),2);
                                }
                            }
                        }
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order"=>$orders,"product"=>$scbp,"return_order"=>$ro,"order_pay_record"=>$opr,'return_order_record'=>$ror,"return_money"=>  array_values($return_money)));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "returnWashOrderShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
  
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-27 09:42:22
     * @Description: 创建套餐卡退货单
     */
    public function createReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "service_card_detail_id"=>'required',
                "reason"=>'required',
                "note"=>'max:140',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=ServiceCardOrder::where("service_card_detail_id",Input::get('service_card_detail_id'))->first();
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($orders->status,array(1417))){
                $response = Lang::get("scs_error.order_return_error_40053");
                break;
            }
            $returnOrder=ReturnServiceCarOrder::where('order_id',$orders->order_id)->whereIn('status',array(0,1))->get();
            if(sizeof($returnOrder)>0){
                $response = Lang::get("scs_error.order_return_error_40043");
                break;
            }           
            $scd=ServiceCardDetail::find(Input::get('service_card_detail_id'));
            if(is_null($scd)||$scd->status!=2){
                $response = Lang::get("scs_error.order_service_card_400138");
                break;
            }
            $scdp=ServiceCardDetailPack::where("service_card_detail_id",Input::get('service_card_detail_id'))->where("curr_number",">",0)->first();
            if(is_null($scdp)){
                $response = Lang::get("scs_error.order_service_card_400139");
                break;
            }

            $ro = new ReturnServiceCarOrder();
            $return_order_id = Common::createOrderId();
            $ro->id = $return_order_id;
            $ro->order_id =$orders->order_id;
            $ro->reason =Input::get('reason');
            $ro->note = Input::get('note')?Input::get('note'):'';
            $ro->amount = 0;
            $ro->created_by = $sc_user->id;
            $ro->created_name = $sc_user->real_name;
            $ro->status = 0;
            $ro->save();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("return_order_id"=>$return_order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "createReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-03-08T14:42:56+0800
     * @return   [type]                   [description]
     * 取消套餐卡退货单
     */
    public function cancelReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $or=ReturnServiceCarOrder::find(Input::get('return_order_id'));
            if(is_null($or) || $or->status==2||$or->status==1){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }            
            $or->status=2;
            $or->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }    
    

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-03-08T14:45:31+0800
     * @return   [type]                   [description]
     * 套餐卡退款单授权
     */
    public function accredit(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ro=ReturnServiceCarOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            
            $orders=ServiceCardOrder::find($ro->order_id);
            $date=date('Y-m-d',time());
            $paytime=explode(' ',$orders->pay_time);
            if($paytime[0]==$date){
                $accredit_type=array(
                    array("type"=>0),
                    array("type"=>1)
                    );
                $me=SCUser::where('status',1)->where('shop_id',$sc_user->shop_id)->where('title',1)->select('id','real_name')->get();
                $result=array('accredit_type'=>$accredit_type,'shop_manager'=>$me);
                
            }else{
                 $accredit_type=array(
                    array("type"=>1)
                    );
                 $temp_ca=CityAuthorization::where("city_id",$sc_user->shop->city_id)->where("return",1)->where("status",1)->select("id","name")->get();
                 $result=array('accredit_type'=>$accredit_type,'approver'=>$temp_ca);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-27 16:04:30
     * @Description:  执行 退款单
     */
    public function implementReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_type"=>'required',
                "return_order_id"=>'required',
                "type"=>'required',
                "code"=>'numeric',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            if(Input::get('type')==1){
                $phone="";
                $area="010";
                $id=Input::get('id');
                $ca=CityAuthorization::find($id);
                $phone=$ca->phone;
                $approver=0;
                $approver_name=$ca->name;
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id',Input::get('return_order_id'))->where("business_type","return_service_card_order")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
        
                //校验验证码是否匹配
                if($record->check_code != Input::get('code')){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                $sc=SCUser::where('shop_id',$sc_user->shop_id)->where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
                $approver=$sc->id;
                $approver_name=$sc->real_name;
            }
            $return_type=json_decode(Input::get('return_type'),1);
            $ro=ReturnServiceCarOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status!=0){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $orders=ServiceCardOrder::find($ro->order_id);

            $s=0;
            foreach($return_type as $_rt){
                $s+=$_rt["amount"];
            }
            $s=(int)bcmul($s,100);
            if($s >$orders->pay_amount){
                $response = Lang::get("scs_error.order_return_error_f_40052");
                break;
            }

            $scd=ServiceCardDetail::find($orders->service_card_detail_id);
            if(is_null($scd)||$scd->status!=2){
                $response = Lang::get("scs_error.order_service_card_400138");
                break;
            }
            $scdp=ServiceCardDetailPack::where("service_card_detail_id",$orders->service_card_detail_id)->where("curr_number",">",0)->first();
            if(is_null($scdp)){
                $response = Lang::get("scs_error.order_service_card_400139");
                break;
            }
            $response=ReturnServiceCarOrder::refund(Input::get('return_order_id'),$approver,$approver_name,$return_type);

            try{
                //if(Config::get('u_meng_push.is_open_u_meng_push') ==1 && Input::get('is_app') ==1){
                NewsLog::NewsPush($orders->user_id,$orders->order_id,5,4,'套餐卡退单完成','套餐卡退单完成，退单日期'.date("Y-m-d",time()));
                //}
            }catch(Exception $e){
                $response = array('code' => -1, 'msg' => '保存套餐卡推送信息失败');
                Log::info("info", array("system" => "scs" ,"event" => "implementReturnOrder", 'input' =>Input::all() ,"output" => $response));
                break;
            }
            // (Input::get('return_order_id'),$roi,$ro->order_id,$sc_user,$ro, $approver,$approver_name,$return_type);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "implementReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-03-08T15:06:32+0800
     * @return   [type]                   [description]
     * 验证发送短信
     */
    public function sendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "return_order_id"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $phone="";
            $area='';
            $return_order_id=Input::get('return_order_id');
            $id=Input::get('id');
            $ca=CityAuthorization::find($id);
            $phone=$ca->phone;
            $time_out_default = Config::get("user.time_out_default");

            
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id',Input::get("return_order_id"))->where("business_type","return_service_card_order")->where("phone",$phone)->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请退货业务，退货单：'.$return_order_id.'，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                            // 'check_code' => $record->check_code // todo 调试使用
                        ));
                    break;
                }else{ //超过限时
                    $record->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请退货业务，退货单：'.$return_order_id.'，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            
            $record = new UserCheckCodeUpgrade;
            $record->business_type="return_service_card_order";
            $record->business_id=Input::get("return_order_id");
            $record->phone=$phone;
            $record->area="";
            $record->check_code=$check_code;
            $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
            $record->send_id=$sms_send_record_id;           
            $record->save();
            
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                )
            );
            
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}